/**
 * Created by Maxwell on 2016/9/26.
 */
"use strict";

var path = require('path'),
    app = require('koa')(),
    koa = require('koa'),
    co = require('co'),
    mount = require('koa-mount'),
    favicon = require("koa-favi"),
    serve = require('koa-static'),
    session = require('koa-generic-session'),
    multer = require('koa-multer'),
    config = require('./config'),
    view = require('koa-view'),
    bodyParser = require('koa-bodyparser'),
    swig = require('swig'),
    commonService = require('./service/common/service');

app.use(require('koa-compress')());
app.use(session());
app.use(bodyParser());

app.use(serve(path.join(__dirname, "assets")));
app.use(serve(path.join(process.cwd(), "bower_components")));

app.use(view(__dirname + '/views', {
    default: 'html',
    cache: false,
    map: {html: 'swig'}
}));
app.use(function *(next) {
    var req = this.req;
    var ip = req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
    var clientToken = yield commonService.getClientToken({
        'client_id': config['client_id'],
        "client_secret": config["client_secret"],
        "grant_type": config["grant_type"]
    });
    this.session.clientToken = JSON.parse(clientToken);
    yield next;
});

app.use(require("./controller/common/router").routes());
app.use(require("./controller/home/router").routes());
app.use(require("./controller/user/router").routes());
app.use(require("./controller/product/router").routes());
app.use(require("./controller/alipay/router").routes());
var mountApp = koa();

mountApp.use(mount(config.prefix ? "/" + config.prefix : '', app));

mountApp.keys = [config.prefix];

module.exports = mountApp;
